<?php session_start(); //Session ?>
<?php include_once( "_db.php" ); //Database ?>
<?php include_once( "funcdef.php" ); //Functions Definition ?>
<?php include_once( "header.php" ); //Header ?>
<?php include_once( "footer.php" ); //Footer ?>
<?php
//include page header
header_template("Payment", $_SERVER['PHP_SELF'], "icon-list");

//db OBJECT invoked!
$db = new DATABASE();

//TMP DEFINES
define("SHOPNAME", "Schanaz");
define("SHOPEMAIL", "shop@sptnkswthrt.com");
define("SHOPEMAILTITLE", "Billing Status");
define("VERIFYKEY", "a873af1f52f8a91750e1f137e5bd8dce");
define("MERCHANTID", "sptnkswthrt");
?>
      <div class="row">
        <div class="span6">
<?php

  $vkey =VERIFYKEY;
  //------ below don't change ---------------
  $tranID   = $_POST['tranID'];
  $orderid  = $_POST['orderid'];
  $status   = $_POST['status'];
  $domain   = $_POST['domain'];
  $amount   = $_POST['amount'];
  $currency = $_POST['currency'];
  $appcode  = $_POST['appcode'];
  $paydate  = $_POST['paydate'];
  $channel  = $_POST['channel'];
  $skey     = $_POST['skey'];
///*
  // All undeclared variables below are coming from POST method
  $key0 = md5($tranID.$orderid.$status.$domain.$amount.$currency);
  $key1 = md5($paydate.$domain.$key0.$appcode.$vkey);
  if( $skey != $key1 ) {
    $status= -1; // invalid transaction
  }
//*/
/*
$status = "00";
$amount = 37.10;
$orderid = "schanaz0000000003";
*/
//-----------------------------------------

  //Get Bill
  $cols = NULL;
  $conds = array();
  $conds[] = array(5, 6);
  $conds[] = array(0, 6);
  $conds[] = array($amount, $orderid);
  $query = $db->db_select("bill", $cols, $conds);
  $result = $db->database->query($query);
  $tmpBill = $result->fetchAll(SQLITE_ASSOC);
    
  //Get Deal
  $cols = NULL;
  $conds = array();
  $conds[] = array(0);
  $conds[] = array(0);
  $conds[] = array($tmpBill[0]['deal_id']);
  $query = $db->db_select("deal", $cols, $conds);
  $queries[] .= $query.";";
  $result = $db->database->query($query);
  $tmpDeal = $result->fetchAll(SQLITE_ASSOC);

  //Get Customer
  $cols = NULL;
  $conds = array();
  $conds[] = array(0);
  $conds[] = array(0);
  $conds[] = array($tmpDeal[0]['customer_id']);
  $query = $db->db_select("customer", $cols, $conds);
  $queries[] .= $query.";";
  $result = $db->database->query($query);
  $tmpCust = $result->fetchAll(SQLITE_ASSOC);
    
  if (($status == "00") || ($status == "22")){
    //status 00-success
    //status 22-pending
    
    if (!empty($tmpBill)) {
      //bill FOUND
      if (($tmpBill[0]['bill_status'] == "new") ||($tmpBill[0]['bill_status'] == "pending")) {
        if ($status == "00") {
          //new/pending == COMPLETED
          //echo "success";
          
          //update bill
          $params = array();
          $params[] = array(3);
          $params[] = array("completed");
          $conds = array();
          $conds[] = array(0);
          $conds[] = array(0);
          $conds[] = array($tmpBill[0]['bill_id']);
          $query = $db->db_update("bill", $params, $conds);
          $queries[] .= $query.";";
          $result = $db->database->query($query);
          
          //update deal
          $params = array();
          $params[] = array(2);
          $params[] = array("paid");
          $conds = array();
          $conds[] = array(0);
          $conds[] = array(0);
          $conds[] = array($tmpBill[0]['deal_id']);
          $query = $db->db_update("deal", $params, $conds);
          $queries[] .= $query.";";
          $result = $db->database->query($query);
          
          //add pay
          $params = array();
          $params[] = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
          $params[] = array ( time()
                            , $amount
                            , $orderid 
                            , $appcode 
                            , $tranID 
                            , $domain 
                            , $status 
                            , $currency 
                            , $paydate
                            , $channel
                            , $skey 
                            , $tmpBill[0]['deal_id']
                            );
          $query = $db->db_insert("pay", $params);
          $queries[] .= $query.";";
          $result = $db->database->query($query);
          $pay_id = $db->database->lastInsertRowid();
          
          //add ship
          $params = array();
          $params[] = array(1, 2, 5);
          $params[] = array ( 0
                            , 0
                            , $tmpBill[0]['deal_id']
                            );
          $query = $db->db_insert("ship", $params);
          $queries[] .= $query.";";
          $result = $db->database->query($query);
          $ship_id = $db->database->lastInsertRowid();
          
          //Get Address
          $cols = NULL;
          $conds = array();
          $conds[] = array(0);
          $conds[] = array(0);
          $conds[] = array($tmpDeal[0]['address_id']);
          $query = $db->db_select("address", $cols, $conds);
          $queries[] .= $query.";";
          $result = $db->database->query($query);
          $tmpAddr = $result->fetchAll(SQLITE_ASSOC);
          
          //send e-mail
          //recipients
          $tmpEmailTo = $tmpAddr[0]["address_fullname"]." <".$tmpCust[0]["customer_email"].">"."\r\n";
          //subject
          $tmpEmailSubject = SHOPNAME." ".SHOPEMAILTITLE."\r\n";
          //message
          $tmpEmailMessage  = file_get_contents("http://stick.sptnkswthrt.com/partial/admin/genemail.php?dealid=".$tmpDeal[0]["deal_id"]."&email=".$tmpCust[0]["customer_email"]."");
          $tmpEmailMessage .= "\r\n";
          //to send HTML mail, the Content-type header must be set
          $tmpEmailHeaders  = "MIME-Version: 1.0"."\r\n";
          $tmpEmailHeaders .= "Content-type: text/html; charset=iso-8859-1"."\r\n";
          //additional headers
          //$tmpEmailHeaders .= "To: ".$tmpAddr[0]["address_fullname"]." <".$tmpCust[0]["customer_email"].">"."\r\n";
          $tmpEmailHeaders .= "From: ".SHOPNAME." <".SHOPEMAIL.">"."\r\n";
          $tmpEmailHeaders .= "Reply-To: ".SHOPNAME." <".SHOPEMAIL.">"."\r\n";
          $tmpEmailHeaders .= "X-Mailer: PHP/".phpversion();
          //mail it
          $result = mail($tmpEmailTo, $tmpEmailSubject, $tmpEmailMessage, $tmpEmailHeaders);
          
          $error_msg = "Payment Succeed.";
          printAlert("success", "Well done!", $error_msg, "#");
        }
        if ($status == "22") {
          //new/pending == PENDING
          //echo "pending";
          
          //update bill
          $params = array();
          $params[] = array(3);
          $params[] = array("pending");
          $conds = array();
          $conds[] = array(0);
          $conds[] = array(0);
          $conds[] = array($tmpBill[0]['bill_id']);
          $query = $db->db_update("bill", $params, $conds);
          $queries[] .= $query.";";
          $result = $db->database->query($query);
          
          $error_msg = "Payment Pending.";
          printAlert("info", "Heads up!", $error_msg, "#");
        }
        /*
        echo "<pre>";
        print_r($tmpBill);
        print_r($queries);
        echo "</pre>";
        */
      } else {
        //expired/canceled/completed
        //something wrong?
        $error_msg = "Bill invalid.";
        printAlert("error", "Oh snap!", $error_msg, "#");
      }
      
      pageRedirect("http://stick.sptnkswthrt.com/partial/admin/transaction.php?dealid=".$tmpDeal[0]['deal_id']."&email=".$tmpCust[0]["customer_email"]);
    } else {
      //bill NOT FOUND
      //something wrong?
      $error_msg = "Bill not found.";
      printAlert("error", "Oh snap!", $error_msg, "#");
    }
  } else {
    //status 11-fail
    //do nothing
    //echo "fail";
    $error_msg = "Payment failed.";
    printAlert("error", "Oh snap!", $error_msg, "#");
    
    pageRedirect("http://stick.sptnkswthrt.com/partial/admin/transaction.php?dealid=".$tmpDeal[0]['deal_id']."&email=".$tmpCust[0]["customer_email"]);
  }
?>
        </div>
      </div>
<?php

//include page footer
footer_template();
?>